﻿using SupermarkedModel;
using Supermarket.Model.MySQL;
using System.Linq;

namespace Supermarket.Client
{
    internal static class ProductDBTransferer
    {
        public static void ReadWriteProductsData()
        {
            SupermarketDbEntities contextEF = new SupermarketDbEntities();

            using (contextEF)
            {
                SupermarketMySQLEntities contextOA = new SupermarketMySQLEntities();

                using (contextOA)
                {
                    var measures = contextOA.Measures.ToList();
                    var existingMeasures = contextEF.Measures.ToDictionary(x => x.ID, x => x.ID);

                    foreach (var measure in measures)
                    {
                        if (!existingMeasures.ContainsKey(measure.ID))
                        {
                            var measureToAdd = new SupermarkedModel.Measure
                            {
                                ID = measure.ID,
                                MeasureName = measure.MeasureName
                            };

                            contextEF.Measures.Add(measureToAdd);
                        }
                    }

                    var vendors = contextOA.Vendors.ToList();
                    var existingVendors = contextEF.Vendors.ToDictionary(x => x.VendorID, x => x.VendorID);

                    foreach (var vendor in vendors)
                    {
                        if (!existingVendors.ContainsKey(vendor.ID))
                        {
                            var vendorToAdd = new SupermarkedModel.Vendor
                            {
                                VendorID = vendor.ID,
                                VendorName = vendor.VendorName
                            };
                            contextEF.Vendors.Add(vendorToAdd);
                        }
                    }

                    var products = contextOA.Products.ToList();
                    var existingProducts = contextEF.Products.ToDictionary(x => x.ID, x => x.ID);

                    foreach (var product in products)
                    {
                        if (!existingProducts.ContainsKey(product.ID))
                        {
                            var productToAdd = new SupermarkedModel.Product
                            {
                                ID = product.ID,
                                VendorID = product.VendorID,
                                ProductName = product.ProductName,
                                MeasureID = product.MeasureID,
                                BasePrice = product.BasePrice
                            };
                            contextEF.Products.Add(productToAdd);
                        }
                    }
                }

                contextEF.SaveChanges();
            }
        }
    }
}
